const { model,Types } = require("mongoose");
let { goodTypeModel } = require("./models/goodTypeModel");

//查询汇总
module.exports.searchGoodsTypedao = async ({ pageIndex, pageSize }) => {
    let res = await goodTypeModel
        .find()
        .limit(pageSize - 0)
        .skip((pageIndex - 1) * (pageSize - 0));
    let totalNum = await goodTypeModel.countDocuments();
    return { result: [...res], totalNum };
};
//单条查询
module.exports.searchGoodsTypeOneDao = async ({
    pageIndex,
    pageSize,
    goodsType,
}) => {
    let res = await goodTypeModel
        .find({ goodsType: { $regex: goodsType, $options: "$i" } })
        .limit(pageSize - 0)
        .skip((pageIndex - 1) * (pageSize - 0));
    let totalNum = await goodTypeModel.countDocuments({
        goodsType: { $regex: goodsType, $options: "$i" },
    });
    return { result: [...res], totalNum };
};
//分页查询
// module.exports.searchGoodsTypePagedao=async (data)=>{
//     // let res=await goodTypeModel.find(goodType)
//     let res=goodTypeModel.find()
//     return res
//     //判断data是否含有分页属性
//     //是 单条
//     //否 分页
// }
//新建

module.exports.addGoodsTypeDao = async (data) => {
    let res = await goodTypeModel.create(data);
    return res;
};

//查询类型是否关联商品
module.exports.searchFlag = async ({_id}) => {
    let res = await goodTypeModel.aggregate([
        {
            $match:{
                "_id":{$eq:new Types.ObjectId(_id)}
            }
        },
        {
            $lookup:{
                from:"good",
                localField:"_id",
                foreignField:"goodsType",
                as:'flag'
            }
        },{
            $unwind:"$flag"
        },{
            $project:{
                id:"$flag._id"
            }
        },
        {
            $group:{
                _id:"$_id",
                count: { $sum : 1}
            }
        }
    ]);
    return res;
};
// 删除
module.exports.deleteGoodsType = async (data) => {
    let res = await goodTypeModel.deleteOne(data);
    return res
};

//编辑

module.exports.updateGoodsType = async ({ _id, goodsType }) => {
    let res = await goodTypeModel.updateOne({ _id }, { goodsType });
    return res;
};
